package com.ljwy.daka;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.ljwy.daka.adapter.ClockAdapter;
import com.ljwy.daka.info.DaKaErrorInfo;
import com.ljwy.daka.info.DaKaInfo;
import com.ljwy.daka.okgoHelper.GsonConvert;
import com.ljwy.daka.okgoHelper.HttpRequestHelper;
import com.ljwy.daka.okgoHelper.JsonCallback;
import com.ljwy.daka.utils.NfcUtils;
import com.ljwy.daka.utils.ToastUtils;
import com.ljwy.daka.utils.cache.ACacheHelper;
import com.lzy.okgo.model.Response;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.ljwy.daka.utils.Constant.DA_KA;
import static com.ljwy.daka.utils.Constant.IP;


public class MainActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.lv)
    ListView lv;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.no_data_tv)
    LinearLayout noDataTv;
    @BindView(R.id.team_tv)
    TextView teamTv;
    @BindView(R.id.count_tv)
    TextView countTv;
    private ClockAdapter adapter;
    private long firstTime;
    private NfcUtils nfcUtils;
    private HashMap<String, String> map;
    private String id;
    private final String DAKA_INFO = "DAKAINFO";
    private ArrayList<DaKaInfo.DataBeanX.DataBean> mDaKaData;
    private ArrayList<DaKaInfo.DataBeanX.DataBean> mTempData = new ArrayList<>();
    private DaKaInfo daKaInfo;
    private ArrayList<DaKaInfo.DataBeanX.DataBean> mDatas = new ArrayList<>();
    private SoundPool soundPool;
    private String no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        nfcUtils = new NfcUtils(this);
        srl.setOnRefreshListener(this);
        map = new HashMap<>();
        no = ACacheHelper.getInstance().getString("NO", "");
        mDaKaData = ACacheHelper.getInstance().get().getAsObject(DAKA_INFO);
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0);
        soundPool.load(mContext, R.raw.duka3, 1);
        if (mDaKaData != null) {
            mDatas.addAll(mDaKaData);
            noDataTv.setVisibility(View.GONE);
        }
        adapter = new ClockAdapter(mContext, mDatas);
        lv.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        nfcUtils.enableForegroundDispatch();
        getList();
        soundPool.autoResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        nfcUtils.disableForegroundDispatch();
        soundPool.autoPause();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        id = nfcUtils.readNFCId(nfcUtils.getNFCTag(intent));
        if (TextUtils.isEmpty(id)) {
            ToastUtils.showShort("nfc读取失败");
        } else {
            upUid(-1);
        }
        soundPool.play(1, 1, 1, 1, 0, 1);
        // String message = nfcUtils.readMessage(intent);
    }

    //获取列表
    private void getList() {
        map.clear();
        map.put("terminal_no", no);
        HttpRequestHelper.getRequest(this,
                IP + DA_KA,
                map, new JsonCallback<String>() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        daKaInfo = GsonConvert.fromJson(response.body(), DaKaInfo.class);
                        teamTv.setText(String.format("团队名：%s", no));
                        countTv.setText(String.format("还剩%s点", daKaInfo.getData().getTotal()));
                        if (daKaInfo.getData() == null || daKaInfo.getData().getData().size() == 0) {
                            noDataTv.setVisibility(View.VISIBLE);
                            lv.setVisibility(View.GONE);
                        } else {
                            mDatas.clear();
                            mDatas.addAll(daKaInfo.getData().getData());
                            if (mDaKaData != null) {
                                mDatas.addAll(mDaKaData);
                            }
                            noDataTv.setVisibility(View.GONE);
                            lv.setVisibility(View.VISIBLE);
                            adapter.notifyDataSetChanged();
                        }
                        srl.setRefreshing(false);
                    }
                });
    }

    //打卡
    private void upUid(final int flag) {
        map.clear();
        if (flag == -1) {
            map.put("cp_no", id);
            map.put("terminal_no", TextUtils.isEmpty(no) ? "" : no);//号码牌
        } else {
            map.put("cp_no", mDaKaData.get(flag).getUid());//卡里数据
            map.put("terminal_no", mDaKaData.get(flag).getCp_no());//输入数据
            map.put("time", mDaKaData.get(flag).getWhen());
        }

        HttpRequestHelper.postRequest(this,
                IP + DA_KA,
                map, false, new JsonCallback<String>() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DaKaErrorInfo errorInfo = GsonConvert.fromJson(response.body(), DaKaErrorInfo.class);
                        if (errorInfo.getMsg().getCode() == 51110) {
                            ToastUtils.showShort(errorInfo.getMsg().getInfo());
                            return;
                        }

                        if (flag != -1) {
                            if (flag == mDaKaData.size() - 1) {
                                ACacheHelper.getInstance().get().remove(DAKA_INFO);
                                mDaKaData.clear();
                            }
                        }
                        getList();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (flag == -1) {
                            DaKaInfo.DataBeanX.DataBean daKaInfo = new DaKaInfo.DataBeanX.DataBean();
                            daKaInfo.setCp_name("上传失败");
                            daKaInfo.setWhen(getCurrentDate());
                            daKaInfo.setCp_no(no);
                            daKaInfo.setUid(id);
                            daKaInfo.setPass(false);
                            mDatas.clear();
                            if (mDaKaData == null) {
                                mTempData.add(daKaInfo);
                                ACacheHelper.getInstance().get().put(DAKA_INFO, mTempData);
                                mDaKaData = ACacheHelper.getInstance().get().getAsObject(DAKA_INFO);
                            } else {
                                mDaKaData.add(daKaInfo);
                            }

                            mDatas.addAll(mDaKaData);
                            ACacheHelper.getInstance().get().put(DAKA_INFO, mDatas);


                            if (MainActivity.this.daKaInfo != null) {
                                mDatas.addAll(MainActivity.this.daKaInfo.getData().getData());
                            }
                            if (mDatas.size() > 0) {
                                noDataTv.setVisibility(View.GONE);
                                lv.setVisibility(View.VISIBLE);
                            } else {
                                noDataTv.setVisibility(View.VISIBLE);
                                lv.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    public static String getCurrentDate() {
        Calendar calendar = Calendar.getInstance();
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(calendar.getTime());
    }

    @Override
    public void onRefresh() {
        mDaKaData = ACacheHelper.getInstance().get().getAsObject(DAKA_INFO);
        getList();
    }


    @Override
    public void onBackPressed() {
        if (mDaKaData != null && mDaKaData.size() > 0) {
            ToastUtils.showShort("您还有本地数据没有上传");
        } else {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                ToastUtils.showShort("再按一次退出程序");
                firstTime = secondTime;
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (soundPool != null) {
            soundPool.release();
        }
    }

    @OnClick(R.id.up_btn)
    public void onViewClicked() {
        mDaKaData = ACacheHelper.getInstance().get().getAsObject(DAKA_INFO);
        if (mDaKaData != null) {
            for (int i = 0; i < mDaKaData.size(); i++) {
                upUid(i);
            }
        } else {
            ToastUtils.showShort("已经全部上传，请勿重复点击");
        }
    }
}